<template>
  <div>
    <el-dialog
      :visible="isShowDialog"
      title="编辑分类"
      @close="btnCancel"
    >
      <!-- 表单 -->
      <el-form ref="addForm" :model="formData" :rules="rules">
        <el-form-item prop="title" label="标题">
          <el-input v-model="formData.title" />
        </el-form-item>
        <el-form-item prop="desc" label="描述">
          <el-input v-model="formData.desc" />
        </el-form-item>
        <el-form-item label="封面">
          <br>
          <!-- 上传图片 -->
          <el-upload

            action="#"
            list-type="picture-card"
            :file-list="fileList"
            :class="{disabel:fileList.length>0}"

            :on-remove="onRemove"
            :on-change="onChange"
            :before-upload="beforeUploadfn"
            :http-request="upload"
            :on-preview="onPreviewfn"
          >
            <i class="el-icon-plus" />
          </el-upload>

          <!-- 进度条 -->
          <el-progress v-if="isShowProgress" :text-inside="true" :stroke-width="26" :percentage="percentage" style="width:146px; " />
        </el-form-item>

      </el-form>
      <!-- 确定或取消 -->
      <el-row slot="footer" type="flex" justify="center">
        <!-- 列被分为24 -->
        <el-col :span="6">
          <el-button type="primary" size="small" @click="btnOk">确定</el-button>
          <el-button size="small" @click="btnCancel">取消</el-button>
        </el-col>
      </el-row>

    </el-dialog>
    <!-- 预览图 -->
    <el-dialog title="预览" :visible="isShowPreview" @close="isShowPreview=false">
      <el-row type="flex" justify="center">
        <img :src="previewURL" alt="">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID84lCMGtGNEpVv64nFQLzMSHqAD4ex1pM',
  SecretKey: 'JL6au1sTnrfCUVFjxub091cwzmIXVDeo'
})
import { getCategoriesById, editCategories, addCategoties } from '@/api/classification'
export default {
  props: {
    isShowDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      previewURL: '', // 预览图
      isShowPreview: false,
      percentage: 0, // 进度条数据
      isShowProgress: false, // 是否隐藏
      fileList: [],
      formData: {
        title: '',
        desc: '',
        image: ''
      },
      rules: {
        title: [{ required: true, message: '不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 预览图
    onPreviewfn(file) {
      this.previewURL = file.url
      this.isShowPreview = true
    },
    upload(params) {
      // 上传时显示进度条
      this.isShowProgress = true
      cos.putObject({
        Bucket: 'hr-1308571603', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percentage = Math.round(progressData.percent * 100)
        }// 上传结束时
      }, (err, data) => {
        console.log(err || data)
        this.fileList[0].url = 'http://' + data.Location
        this.fileList[0].status = 'success'
        setTimeout(() => {
          this.isShowProgress = false
        }, 1000)
      })
    },
    // 上传前校验
    beforeUploadfn(file) {
      // 限制大小
      const maxSize = 2 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.warning('图片大小不能大于2M')
        return false
      }
      const whiteList = ['image/jpeg', 'image/png', 'image/jpg']
      if (!whiteList.includes(file.type)) {
        this.$message.warning('图片目前只支持jpeg,png,jpg')
        return false
      }
    },
    onRemove(file, newFileList) {
      this.fileList = newFileList
    },
    onChange(file, newFileList) {
      this.fileList = newFileList
    },
    async getFromData(id) {
      const { data } = await getCategoriesById(id)
      this.formData = data
      this.fileList = [{ url: data.image }]
    },
    // 确定
    async btnOk() {
      if (this.formData.id) {
        // 判断图片是否为空时
        if (!this.fileList[0]) {
          this.fileList[0] = { url: 'http://#' }
        }
        const img = { image: this.fileList[0].url }
        // 修改
        await editCategories({ ...this.formData, ...img })
        await this.$message.success('修改成功')
      } else {
      // 添加
      // 判断图片是否为空时
        if (!this.fileList[0]) {
          delete this.formData.image
          await addCategoties(this.formData)
          await this.$message.success('添加成功')
          // 关闭界面
          await this.$emit('update:isShowDialog', false)
          // 刷新页面
          await this.$emit('addinit')
          return
        }
        const img = { image: this.fileList[0].url }
        await addCategoties({ ...this.formData, ...img })
        await this.$message.success('添加成功')
      }
      // 关闭界面
      this.$emit('update:isShowDialog', false)
      // 刷新页面
      this.$emit('init')
    },
    // 取消
    btnCancel() {
    // 清空表单
      this.$refs.addForm.resetFields()
      // 清空图片
      this.fileList = []
      this.formData = {}
      // 隐藏
      this.$emit('update:isShowDialog', false)
    }
  }
}
</script>

<style lang="scss" scoped>
.disabel{
  ::v-deep .el-upload--picture-card{
    display: none;

  }
}
</style>
